<template>
  <view class="container">
    <view v-if="isLoggedIn" class="logged-in">
      <!-- 显示用户信息 -->
      <text class="welcome-msg">欢迎回来，{{ username }}！</text>
      <view class="user-info">
        <text>用户等级：{{ level }}</text><p></p>
        <text>余额：¥{{ balance }}</text>
      </view>
      <button @click="logout" class="btn logout-btn">退出登录</button>
      
      <!-- 购物清单 -->
      <view v-if="shoppingList.length" class="shopping-list-container">
        <text class="shopping-list-title">购物清单：</text>
        <view v-for="(item, index) in paginatedList" :key="item.id" class="shopping-item">
          <text><strong>商品名称：</strong>{{ item.product_name }}</text>
          <text><strong>数量：</strong>{{ item.quantity }} 个</text>
          <text><strong>单价：</strong>¥{{ item.price }}</text>
          <text><strong>总价：</strong>¥{{ item.total_price }}</text>
          <text><strong>购买时间：</strong>{{ formatDate(item.purchase_time) }}</text>
		  <text><strong>状态：</strong>{{ item.staus }}</text>
		  
          <!-- 删除按钮 -->
          <button v-if="item.staus === '受理中'" @click="deleteOrder(item.id)" class="btn delete-btn">
            删除订单
          </button>
        </view>
        
        <!-- 分页控制 -->
        <view class="pagination">
          <button 
            @click="previousPage" 
            :disabled="currentPage === 1" 
            class="btn page-btn">
            上一页
          </button>
          <text class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</text>
          <button 
            @click="nextPage" 
            :disabled="currentPage === totalPages" 
            class="btn page-btn">
            下一页
          </button>
        </view>
      </view>
      <view v-else>
        <text class="no-items">购物清单为空</text>
      </view>
    </view>
    
    <view v-else class="not-logged-in">
      <!-- 登录和注册表单 -->
      <view v-if="isLogin" class="auth-form">
        <input v-model="username" placeholder="用户名" class="input-field" />
        <input v-model="password" type="password" placeholder="密码" class="input-field" />
        <button @click="handleLogin" class="btn login-btn">登录</button>
      </view>
      
      <view v-else class="auth-form">
        <input v-model="username" placeholder="用户名" class="input-field" />
        <input v-model="password" type="password" placeholder="密码" class="input-field" />
        <button @click="handleRegister" class="btn register-btn">注册</button>
      </view>

      <text v-if="errorMessage" class="error-msg">{{ errorMessage }}</text>

      <button @click="toggleAuth" class="btn toggle-auth-btn">
        {{ isLogin ? '切换到注册' : '切换到登录' }}
      </button>
    </view>

    <modal v-if="isModalVisible" @close="hideModal">
      <text>{{ errorMessage }}</text>
    </modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
      isModalVisible: false, // 控制弹窗显示与隐藏
      errorMessage: '',  // 错误信息
      username: '',  // 用户名
      password: '',  // 密码
      isLogin: true,  // 是否显示登录表单
      isLoggedIn: false,  // 用户是否登录
      level: '',  // 用户等级
      balance: 0,  // 用户余额
      shoppingList: [],  // 所有购物清单
      currentPage: 1,  // 当前页码
      itemsPerPage: 3,  // 每页显示的商品数量
      totalPages: 1,  // 总页数
      checkLoginInterval: null, // 定时器标识
      staus: '',
    };
  },

  computed: {
    // 分页后的购物清单
    paginatedList() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      const endIndex = startIndex + this.itemsPerPage;
      return this.shoppingList.slice(startIndex, endIndex);
    },
  },

  methods: {
    // 日期格式化函数
    formatDate(dateStr) {
      const date = new Date(dateStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    // 删除订单
    deleteOrder(orderId) {
      uni.request({
        url: 'https://api.dmitai.vip/deleteOrder',  // 后端删除订单接口
        method: 'POST',
        data: {
          orderId: orderId,
        },
        success: (res) => {
          if (res.data.success) {
            uni.showToast({
              title: '订单删除成功',
              icon: 'success',
              duration: 2000
            });
            this.fetchShoppingList(); // 重新获取购物清单
          } else {
            uni.showToast({
              title: res.data.message || '删除订单失败',
              icon: 'none',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          uni.showToast({
            title: '请求失败，请稍后重试',
            icon: 'none',
            duration: 2000
          });
        }
      });
    },

    // 显示上一页
    previousPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    // 显示下一页
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },

    fetchShoppingList() {
      uni.request({
        url: 'https://api.dmitai.vip/getShoppingList', 
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          if (res.data.success) {
            this.shoppingList = res.data.shoppingList || [];
            this.shoppingList.sort((a, b) => new Date(b.purchase_time) - new Date(a.purchase_time));
            this.totalPages = Math.ceil(this.shoppingList.length / this.itemsPerPage);
            this.paginateShoppingList();
          } else {
            this.shoppingList = [];
            this.errorMessage = res.data.message || '获取购物清单失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    paginateShoppingList() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      this.currentShoppingList = this.shoppingList.slice(start, end); // 当前页的数据
    },

    handleLogin() {
      this.errorMessage = '';  // 清空错误信息

      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }

      uni.request({
        url: 'https://api.dmitai.vip/login',
        method: 'POST',
        data: {
          username: this.username,
          password: this.password,
        },
        success: (res) => {
          if (res.data.success) {
            uni.setStorageSync('token', res.data.token);
            uni.setStorageSync('username', this.username);
            this.isLoggedIn = true;
            this.fetchUserLevel();
            this.fetchUserBalance();
            this.fetchShoppingList();
            this.errorMessage = '';
          } else {
            this.errorMessage = res.data.message || '登录失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    fetchUserLevel() {
      uni.request({
        url: 'https://api.dmitai.vip/getUserLevel',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          if (res.data.success) {
            this.level = res.data.level;
          } else {
            this.level = '未知';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.level = '未知';
        }
      });
    },

    fetchUserBalance() {
      uni.request({
        url: 'https://api.dmitai.vip/getUserBalance',
        method: 'GET',
        data: { username: this.username },
        success: (res) => {
          if (res.data.success) {
            this.balance = res.data.balance || 0;
          } else {
            this.balance = 0;
            this.errorMessage = res.data.message || '获取用户余额失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    handleRegister() {
      this.errorMessage = '';

      if (!this.username || !this.password) {
        this.errorMessage = '用户名和密码不能为空';
        return;
      }

      uni.request({
        url: 'https://api.dmitai.vip/register',
        method: 'POST',
        data: {
          username: this.username,
          password: this.password,
        },
        success: (res) => {
          if (res.data.success) {
            uni.showToast({
              title: '注册成功',
              icon: 'success',
            });
            this.toggleAuth();
          } else {
            this.errorMessage = res.data.message || '注册失败';
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          this.errorMessage = '请求失败，请稍后重试';
        }
      });
    },

    logout() {
      this.isLoggedIn = false;
      uni.removeStorageSync('token');
      uni.removeStorageSync('username');
    },

    toggleAuth() {
      this.isLogin = !this.isLogin;
    },

    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      const username = uni.getStorageSync('username');
      if (token && username) {
        this.isLoggedIn = true;
        this.username = username;
        this.fetchUserLevel();
        this.fetchUserBalance();
        this.fetchShoppingList();
      } else {
        this.isLoggedIn = false;
      }
    },
  },

  created() {
    this.checkLoginStatus();
    // 设置定时器，每8秒检查一次登录状态
    this.checkLoginInterval = setInterval(() => {
      this.checkLoginStatus();
    }, 8000);
  },

  beforeDestroy() {
    // 清除定时器
    clearInterval(this.checkLoginInterval);
  },
};
</script>



<style scoped>
/* 样式保持不变，只需要调整分页按钮的样式 */
.container {
  background: linear-gradient(135deg, #6e7dff, #34d399);
  min-height: 100vh;
  font-family: 'Roboto', sans-serif;
  padding: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logged-in, .not-logged-in {
  width: 100%;
  max-width: 500px;
  background-color: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.welcome-msg {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.user-info {
  font-size: 16px;
  color: #555;
  margin-bottom: 20px;
}

.btn {
  width: 100%;
  padding: 12px;
  border-radius: 10px;
  border: none;
  font-size: 18px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.logout-btn {
  background-color: #f44336;
  color: white;
}

.shopping-list-container {
  width: 100%;
  margin-top: 20px;
}

.shopping-list-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.shopping-item {
  background-color: #f9f9f9;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.shopping-item text {
  display: block;
  font-size: 16px;
  margin-bottom: 5px;
}

.error-msg {
  color: red;
  text-align: center;
}

.input-field {
  width: 100%;
  padding: 12px;
  border-radius: 10px;
  border: 1px solid #ccc;
  margin-bottom: 15px;
  font-size: 16px;
}

.no-items {
  text-align: center;
  font-size: 18px;
}

@media (max-width: 600px) {
  .container {
    padding: 15px;
  }

  .logged-in, .not-logged-in {
    padding: 20px;
  }
}
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.page-btn {
  width: 100px;
  padding: 10px;
  border-radius: 8px;
  background-color: #007bff;
  color: white;
  font-size: 16px;
}

.page-info {
  font-size: 16px;
}

.no-items {
  text-align: center;
  font-size: 18px;
}
</style>
